using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Text;
using System.Windows;
using Gko.Utils;
using Gko.Wpf.Mvvm.Interfaces;

namespace Gko.Wpf.Mvvm
{
	public abstract class ViewModelBase : DisposableBindableBase, IViewModel, INotifyComposablePartCatalogChanged
	{
		[Import(typeof(IViewModelContext))]
		private readonly IViewModelContext context;
		private readonly Lazy<Background> background;

		/// <exception cref="ArgumentNullException"><c>context</c> is null.</exception>
		protected ViewModelBase()
		{
			this.background = new Lazy<Background>(() => this.context.SynchronizationContext.CreateBackground());
		}

		protected Background Background
		{
			get
			{
				return this.background.Value;
			}
		}

		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
		protected bool IsUIThread
		{
			get
			{
				return Application.Current.Dispatcher.CheckAccess();
			}
		}

		#region IViewModel Members

		public IViewModelContext Context
		{
			get
			{
				return this.context;
			}
		}

		[SubscribeToEvent(typeof(FrameworkElement), "LoadedEvent")]
		public virtual void OnLoaded()
		{
		}

		[SubscribeToEvent(typeof(FrameworkElement), "UnloadedEvent")]
		public virtual void OnUnloaded()
		{
			this.Dispose();
		}

		#endregion

		public event EventHandler<ComposablePartCatalogChangeEventArgs> Changed;
		public event EventHandler<ComposablePartCatalogChangeEventArgs> Changing;
	}
}